import type {
  ReactElement,
  ReactPortal,
} from 'react'
import { createPortal } from 'react-dom'
import { canUseDom } from '@/library/tool-kits/can-use-dom'
import {
  resolveContainer,
  type GetContainer,
} from './get-container'

/**
 * @param {GetContainer} getContainer - 指定挂载的 HTML节点
 * @param {ReactElement} node - 需挂载元素
 * @returns {ReactPortal | ReactElement}
 */
export function renderToContainer(
  getContainer: GetContainer,
  node: ReactElement,
): ReactPortal | ReactElement {
  if (canUseDom && getContainer) {
    const container = resolveContainer(getContainer)
    return createPortal(node, container as Element)
  }

  return node
}
